package top.zhaoyuliu.logbook.client.connect.client;

import java.io.UnsupportedEncodingException;

import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;

import cn.hutool.json.JSONUtil;
import top.zhaoyuliu.logbook.client.builder.TaskInfo;
import top.zhaoyuliu.logbook.client.connect.base.AbstractAioHandler;
import top.zhaoyuliu.logbook.client.connect.packet.LbPacket;
import top.zhaoyuliu.logbook.client.connect.packet.PacketBuilder;
import top.zhaoyuliu.logbook.client.connect.packet.PacketType;
import top.zhaoyuliu.logbook.client.constant.Const;
import top.zhaoyuliu.logbook.client.queue.LbQueue;
import top.zhaoyuliu.logbook.client.thread.ThreadPool;
import top.zhaoyuliu.logbook.client.utils.IPUtils;

/**
 * 
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: BlockClientAioHandler.java
 * @Prject: logbook-client
 * @Package: top.zhaoyuliu.logbook.client.connect.client
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月22日 下午3:23:22
 * @version: V1.0
 */
public class LbClientAioHandler extends AbstractAioHandler implements ClientAioHandler {
	/**
	 * 处理消息
	 */
	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
		ThreadPool.INSTANCE.executor().execute(new Runnable() {
			@Override
			public void run() {
				try {
					LbPacket lbPacket = (LbPacket) packet;
					byte[] body = lbPacket.getBody();
					byte type = lbPacket.getType();
					if (body != null) {
						if (PacketType.SELECTTASK == type) {
							String data = new String(body, Const.CHARSET);
							TaskInfo taskInfo = JSONUtil.toBean(data, TaskInfo.class);
							LbQueue.sendToCluster(taskInfo, channelContext);
						}
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

		});
	}

	public Packet heartbeatPacket(ChannelContext channelContext) {
		LbPacket packet = new PacketBuilder().setType(PacketType.CLIENT_HEART_BEAT).setBody(IPUtils.getIP()).build();
		return packet;
	}

}
